<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\service;

use app\common\model\log\BaiyangApiLogs as BaiyangApiLogsModel;

class BaiyangApiService {

    use \app\common\traits\ApiPost;

    private $_appSecret = '';
    
    public function __construct() {
        $this->_appSecret = config('BAIYANG_API_APP_SECRET');
    }

    public function send($fuc, $params) {

        $params['sign'] = $this->_createSign($params);

        $url = $this->_createUrl($fuc);

        $BaiyangApiLogsModel = new BaiyangApiLogsModel();

        try {
            unset($params['key']);
            $res = $this->_postArr($url, $params, 'post');
        } catch (\Exception $e) {

            $BaiyangApiLogsModel->addLog($params, ['msg' => $e->getMessage()], 0, $url);
            $this->outPutError(['msg' => $e->getMessage()]);
        }

        $res = json_decode($res, true);

        $BaiyangApiLogsModel->addLog($params, $res, 1, $url);

        return $res;
    }

    private function _createUrl($fuc) {
        $url = config('baiyangMallURL');

        $url = $url . $fuc;

        return $url;
    }

    private function _createSign(&$params) {
        $urlStr = '';
        ksort($params);

        $params['key'] = $this->_appSecret;

        foreach ($params as $keys => $value) {
            $urlStr .= strtolower($keys) . '=' . $value . '&';
        }

        $sign = md5(rtrim($urlStr, '&'));

        return $sign;
    }

}
